package io.chenglicun.common.trans.util;

import cn.hutool.extra.spring.SpringUtil;
import io.chenglicun.common.page.PageData;
import io.chenglicun.common.trans.core.TransClassMeta;
import io.chenglicun.common.trans.manager.TransClassMetaManager;
import io.chenglicun.common.trans.service.TransService;
import io.chenglicun.common.utils.Result;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TransUtil {

    /**
     * 翻译工具
     *
     * @param obj      需要翻译的对象
     * @param objClass 需要翻译的对象的实际class
     * @return 是否翻译成功
     */
    public static boolean trans(Object obj, Class<?> objClass) {
        if (obj == null) {
            return false;
        }
        if (objClass.getName().startsWith("java.")) {
            return false;
        }
        TransClassMeta info = TransClassMetaManager.getTransClassMeta(objClass);
        if (!info.needTrans()) {
            return false;
        }
        Object trans = obj;
        if (trans instanceof Result) {
            Result<?> result = (Result<?>) trans;
            trans = result.getData();
            if (trans instanceof PageData) {
                PageData<?> page = (PageData<?>) trans;
                trans = page.getList();
            }
        }
        TransService transService = TransServiceHolder.get();
        transService.trans(trans, info);
        return true;
    }

    static class TransServiceHolder {
        private static final TransService INSTANCE;

        static {
            INSTANCE = SpringUtil.getBean(TransService.class);
        }

        public static TransService get() {
            return INSTANCE;
        }
    }

}
